//
//  FiltrateCategoryPickerCell.m
//  pmm
//
//  Created by WTFSSD on 2017/7/28.
//  Copyright © 2017年 WTFSSD. All rights reserved.
//

#import "FiltrateCategoryPickerCell.h"
#import "MoreBrandTableViewController.h"


#pragma mark - 品牌item _all_brand_Item
//-------------*************--------------
@interface _CategoryItem:UICollectionViewCell

/**labe*/
@property(nonatomic,strong)UILabel* textLabel;

/**是否选择*/
@property(nonatomic)BOOL checked;

@end

@implementation _CategoryItem

-(UILabel*)textLabel{
    if (!_textLabel) {


        _textLabel = [HMLabel createLabelWithText:@"" andTextColor:HexColor(0x333333) andBgColor:HexColor(0xf0f2f5) andFont:[UIFont fontWithName:default_fontname size:autoScaleW(13)] andTextAlignment:NSTextAlignmentCenter];

        [self.contentView addSubview:_textLabel];

        _textLabel.layer.cornerRadius = 4;
        _textLabel.layer.masksToBounds = YES;

        [_textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(UIEdgeInsetsZero);
        }];
    }
    return _textLabel;
    
}

-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        self.textLabel.hidden = NO;
    }
    return self;
}

-(void)setChecked:(BOOL)checked{
    _checked = checked;
    if (_checked) {
        self.textLabel.textColor = HexColor(0xffffff);
        self.textLabel.backgroundColor = HexColor(0x499CF4);
    }else{
        self.textLabel.textColor = HexColor(0x333333);
        self.textLabel.backgroundColor = HexColor(0xf0f2f5);
    }
}


@end

#pragma mark - 自定义全部品牌按钮 _all_brand_Item

@interface _all_brand_Item:UICollectionViewCell

@property(nonatomic,strong)UILabel* textLabel;
@property (nonatomic,strong) UIImageView *all_imageView;

@end

@implementation _all_brand_Item


-(instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        [self initSubViews];
    }
    return self;
}
-(void)initSubViews{
    WeakSelf(weakSelf);

    _textLabel = [ HMLabel createLabelWithText:@"全部品牌" andTextColor:RGBA(153,153,153,1)andBgColor:nil andFont:[UIFont fontWithName:default_fontname size:autoScaleW(13)] andTextAlignment:NSTextAlignmentCenter];

    [self addSubview:_textLabel];

    [_textLabel mas_makeConstraints:^(MASConstraintMaker *make) {

        make.centerY.mas_equalTo(weakSelf);
        make.left.mas_equalTo(0);
        make.width.mas_equalTo(weakSelf.frame.size.width - autoScaleW(20));
        make.height.mas_equalTo(weakSelf);

    }];

    _all_imageView =  [[UIImageView alloc] init];

    [_all_imageView setImage:[UIImage imageNamed:@"icon_arrow_right_gray"]];

    [self addSubview:_all_imageView];
    [_all_imageView mas_makeConstraints:^(MASConstraintMaker *make) {

        make.centerY.mas_equalTo(weakSelf);
        make.right.mas_equalTo(0);
        make.width.mas_equalTo(autoScaleW(12));
        make.height.mas_equalTo(autoScaleH(20));
        
    }];

}


@end

#pragma mark - 筛选 cell
//-------------*************--------------
//
@interface FiltrateCategoryPickerCell()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong)UIButton * expandButton;


@property(nonatomic,strong)NSMutableArray * mSelectedCategorys;

@property(nonatomic,strong)UIButton * lastButton;

///**容器 CollectionView*/
@property(nonatomic,strong)UICollectionView* collectionView;

///**显示条目数*/
@property(nonatomic,assign)NSInteger displayCount;

///**弹出菜单*/
@property(nonatomic,strong)WEPopoverController* pop;
@property(nonatomic,strong)MoreBrandTableViewController * brandVc;
//
@end
//
@implementation FiltrateCategoryPickerCell

-(WEPopoverController *)pop{
   WeakSelf(weakself);
    if (!_pop) {
        MoreBrandTableViewController * vc =  [MoreBrandTableViewController controllerWith:UITableViewStylePlain];
        vc.dataSource = self.categorys;
        vc.selectedCategory = self.mSelectedCategorys;
        vc.didSelectedCallBack = ^(NSArray *selectedCategory) {
            [weakself.mSelectedCategorys removeAllObjects];
            [weakself.mSelectedCategorys addObjectsFromArray:selectedCategory];
            [weakself.collectionView reloadData];
            [weakself postNote];
        };
        UINavigationController*nvc = [[UINavigationController alloc] initWithRootViewController:vc];
        WEPopoverController * pop = [[WEPopoverController alloc]
                                     initWithContentViewController:nvc];
        pop.backgroundColor = RGBA(0, 0, 0, 0.5);
        pop.animationType = WEPopoverAnimationTypeSlide;
        
        pop.popoverLayoutMargins = UIEdgeInsetsMake(-20, 0, 0, 0);
        pop.containerViewProperties = [WEPopoverController defaultContainerViewProperties];
        pop.containerViewProperties.contentMargins = UIEdgeInsetsZero;
        pop.containerViewProperties.backgroundMargins = UIEdgeInsetsZero;
        pop.gestureBlockingEnabled = NO;
        self.brandVc = vc;
        _pop = pop;
    }
    return _pop;
}
-(NSMutableArray*)mSelectedCategorys{
    if (!_mSelectedCategorys) {
        _mSelectedCategorys = [NSMutableArray array];
    }
    return _mSelectedCategorys;
}

-(UICollectionView *)collectionView{
    if (!_collectionView) {

        NSLog(@"self.contentView.frame.size.width ===== %f",self.contentView.frame.size.width);
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        layout.itemSize = CGSizeMake((autoScaleW(320) - autoScaleW(30) )/3, autoScaleH(26));
        layout.sectionInset = UIEdgeInsetsMake(0, autoScaleW(5), 0, autoScaleW(5));

        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.backgroundColor = UIColor.whiteColor;
        _collectionView.dataSource = self;
        _collectionView.delegate = self;
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        
        [_collectionView registerClass:[_CategoryItem class] forCellWithReuseIdentifier:@"_CategoryItem"];

         [_collectionView registerClass:[_all_brand_Item class] forCellWithReuseIdentifier:@"_all_brand_Item"];
        
        [self.contentView addSubview:_collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.bottom.equalTo(self.contentView);
            make.top.equalTo(self.titleView.mas_bottom).offset(autoScaleH(10));
        }];
    }
    return _collectionView;
}

-(void)initSubViews{
    [super initSubViews];
    
    UIButton * expandButton = [UIButton buttonWithType:UIButtonTypeCustom];

    expandButton.frame = CGRectMake(0, 0, autoScaleW(60), autoScaleH(18));
    [expandButton setTitle:@"全部" forState:UIControlStateNormal];
    [expandButton setTitle:@"全部" forState:UIControlStateSelected];
    [expandButton setImage:[UIImage imageNamed:@"icon_arrow_down_gray"] forState:UIControlStateNormal];
    [expandButton setTitleColor:RGB(135, 139, 142) forState:UIControlStateNormal];
    [expandButton setTitleColor:RGB(135, 139, 142) forState:UIControlStateSelected];
    [expandButton setImage:[UIImage imageNamed:@"icon_arrow_up_gray"] forState:UIControlStateSelected];
    expandButton.titleEdgeInsets = UIEdgeInsetsMake(0, autoScaleW(-35), 0, 0);
    expandButton.imageEdgeInsets = UIEdgeInsetsMake(0, autoScaleW(40), 0, 0);

    expandButton.titleLabel.font = [UIFont fontWithName:default_fontname size:autoScaleW(13)];;
    [expandButton addTarget:self action:@selector(expandButtonClick:) forControlEvents:UIControlEventTouchUpInside];
    self.expandButton = expandButton;
    self.extraView = expandButton;

    self.hyb_lastViewInCell =  self.collectionView;

}

-(void)expandButtonClick:(UIButton*)sender{

    if (self.categorys.count>self.maxDisplayCount) {
        sender.selected = !sender.selected;
        [[NSNotificationCenter defaultCenter] postNotificationName:ChangeExpandNotificationKey object:self.indexPath userInfo:@{FiltrateCategoryPickerCellExpandSatusKey:@(sender.selected),FiltrateCategoryPickerCellCategorysKey:self.maxDisplayCount>0?[self.categorys map:^id(id obj, int index) {
            if (index<self.maxDisplayCount) {
                return obj;
            }
            return nil;
        }]:self.categorys}];
    }
}

-(void)categoryItemClick:(NSIndexPath*)indexPath{
    if ([self.mSelectedCategorys indexOfObject:self.categorys[indexPath.item]]!=NSNotFound) {
        [self.mSelectedCategorys removeObject:self.categorys[indexPath.item]];
    }else{
        [self.mSelectedCategorys addObject:self.categorys[indexPath.item]];
    }
    [self.collectionView reloadData];
    [self postNote];
}


-(void)postNote{
     [[NSNotificationCenter defaultCenter] postNotificationName:SelectedCategoryNotificationKey object:self.indexPath userInfo:@{FiltrateSelectedCategorysKey:[NSArray arrayWithArray:self.mSelectedCategorys],FiltrateSelectedTitleKey:self.title}];
}

-(void)setExpaned:(BOOL)expaned{
    _expaned = expaned;
    self.expandButton.selected = expaned;
    [self.collectionView reloadData];
}

-(void)setSelectedCategorys:(NSArray *)selectedCategorys{
    _selectedCategorys = selectedCategorys;
    [self.mSelectedCategorys removeAllObjects];
    [self.mSelectedCategorys addObjectsFromArray:selectedCategorys];
    [self setNeedsLayout];
}

-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    NSInteger count = 0;
    if (self.maxDisplayCount <= 0) {//全部显示
        if (self.expaned) {//展开
            count = self.categorys.count;
        }else{//收起
            count = self.categorys.count > 3 ? 3:self.categorys.count;
        }
    }else{//限制显示
        if (self.expaned) {//展开
            count = self.categorys.count>self.maxDisplayCount?self.maxDisplayCount:self.categorys.count;
        }else{//收起
            if (self.categorys.count<self.maxDisplayCount) {
                count = self.categorys.count > 3 ? 3:self.categorys.count;
            }else{
                count = self.maxDisplayCount > 3 ? 3:self.maxDisplayCount;
            }
        }
    }
    self.displayCount = count;
    return count;
}

-(void)setCategorys:(NSArray *)categorys{
    _categorys = categorys;

}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{



    if ([self isMore:indexPath]) {

    _all_brand_Item * item = [collectionView dequeueReusableCellWithReuseIdentifier:@"_all_brand_Item" forIndexPath:indexPath];


        return item;
//        item.textLabel.text = @"更多";
//        item.checked = NO;
    }else{

        _CategoryItem * item = [collectionView dequeueReusableCellWithReuseIdentifier:@"_CategoryItem" forIndexPath:indexPath];
        item.textLabel.text = self.categorys[indexPath.row][@"label"];
        item.checked = [self.mSelectedCategorys indexOfObject:self.categorys[indexPath.row]]!= NSNotFound;


        return item;
    }
    

}

-(BOOL)isMore:(NSIndexPath*)indexPath{
    
    if (self.categorys.count > self.maxDisplayCount&&self.maxDisplayCount>3) {
        if (self.expaned) {
            if (indexPath.row == self.maxDisplayCount - 1) {
                return YES;
            }
        }
    }
    
    if (self.categorys.count>self.maxDisplayCount&&self.maxDisplayCount <=3) {
        if (indexPath.row == self.maxDisplayCount - 1) {
            return YES;
        }
    }
    
    return NO;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if([self isMore:indexPath]){
        self.brandVc.selectedCategory = self.mSelectedCategorys;
        [self.pop presentPopoverFromRect:CGRectMake(SCREEN_WIDTH, 0, SCREEN_WIDTH, SCREENH_HEIGHT) inView:self permittedArrowDirections:UIPopoverArrowDirectionRight animated:YES];
    }else{
        [self categoryItemClick:indexPath];
    }
}
@end



NSString * ChangeExpandNotificationKey = @"ChangeExpandNotificationKey";

NSString * SelectedCategoryNotificationKey = @"SelectedCategoryNotificationKey";

NSString * FiltrateCategoryPickerCellExpandSatusKey = @"FiltrateCategoryPickerCellExpandSatusKey";

NSString * FiltrateCategoryPickerCellCategorysKey = @"FiltrateCategoryPickerCellCategorysKey";

NSString * FiltrateSelectedCategorysKey = @"FiltrateSelectedCategorysKey";

NSString * FiltrateSelectedTitleKey = @"FiltrateSelectedTitleKey";
